package com.binvshe.binvshe.mine.corporation.fragment;


import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.Account;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.account.utils.FragmentUtils;
import com.binvshe.binvshe.mine.MineInfoActivity;
import com.binvshe.binvshe.mine.utils.HeadUploadUtils;
import com.binvshe.binvshe.mine.view.ChooseCityDialog;
import com.pachong.android.baseuicomponent.fragment.BaseFragment;
import com.pachong.android.framework.picture.clipimage.PhotoActionHelper;
import com.pachong.android.framework.picture.picker.release.SelectAlbumActivity;
import com.pachong.android.framework.picture.picker.utils.FileManager;
import com.pachong.android.frameworkbase.dialog.IOSAlertListFragment;
import com.pachong.android.frameworkbase.imageloader.ImageLoader;
import com.pachong.android.frameworkbase.utils.BitmapUtil;
import com.pachong.android.frameworkbase.utils.EasyToast;

import butterknife.Bind;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * A simple {@link Fragment} subclass.
 */
public class CreatCropFragment extends BaseFragment {


    @Bind(R.id.mImgCorpHead)
    CircleImageView mImgCorpHead;
    @Bind(R.id.mEtCorpName)
    EditText mEtCorpName;
    @Bind(R.id.mTvCorpAddress)
    TextView mTvCorpAddress;

    private String mUrlClubHead;
    private String mProvince;
    private String mCity;
    private String mHeadUrl;
    private String mFilename = "/" + System.currentTimeMillis() + ".png";
    private String mFilePath = null;

    public CreatCropFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        mFilePath = FileManager.getImagePath(getActivity());
        initToolBar();
        return view;
    }

    private void initToolBar() {
        showToolbar();
        getCustomToolbar().setTitle("创建社团");
        getCustomToolbar().enableBackButton();
        getCustomToolbar().addRightButton("下一步", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String corpName = mEtCorpName.getText().toString().trim();
                if (TextUtils.isEmpty(mUrlClubHead)) {
                    EasyToast.showToast(getActivity(), "请添加社团头像");
                    return;
                }
                if (TextUtils.isEmpty(corpName)) {
                    EasyToast.showToast(getActivity(), "社团名称不能为空");
                    return;
                }
                if (corpName.length() < 2 || corpName.length() > 10) {
                    EasyToast.showToast(getActivity(), "社团名称为2-10个字");
                    return;
                }
                if (mTvCorpAddress.length() < 4) {
                    EasyToast.showToast(getActivity(), "请选择地址");
                    return;
                }
                FragmentUtils.addFragment(getFragmentManager(),
                        R.id.corpContainer,
                        CorpInfoFragment.newInstance(corpName, mProvince, mCity, mUrlClubHead));
            }
        });
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.frag_creat_crop, null);
    }

    @OnClick({R.id.mImgCorpHead, R.id.mTvCorpAddress})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mImgCorpHead:
                showIOSAlertFrag();
                break;
            case R.id.mTvCorpAddress:
                ChooseCityDialog chooseCityDialog = new ChooseCityDialog();
                chooseCityDialog.show(getFragmentManager(), "tag");
                chooseCityDialog.setOnClickable(new ChooseCityDialog.ProvinceClickable() {
                    @Override
                    public void btnEnter(String province, String city) {
                        mProvince = province;
                        mCity = city;
                        mTvCorpAddress.setText(mProvince + " " + mCity);
                    }
                });
                break;
        }
    }

    private void showIOSAlertFrag() {
        final IOSAlertListFragment diaFrag = new IOSAlertListFragment();
        String strArr = "从照片库选择";
        diaFrag.setActionList(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    Intent intentPickPhoto = new Intent(getContext(), SelectAlbumActivity.class);
                    intentPickPhoto.putExtra(SelectAlbumActivity.RELEASE_IMGS_NUM, 0);
                    intentPickPhoto.putExtra(SelectAlbumActivity.INTENT_MAX_NUM, 1);
                    startActivityForResult(intentPickPhoto, MineInfoActivity.SELECT_ALBUM_REQUEST);
                }
                diaFrag.dismiss();
            }
        }, strArr).show(getFragmentManager());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("onActivityResult: ", "onActivityResult");
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == MineInfoActivity.SELECT_ALBUM_REQUEST) {
                mHeadUrl = data.getExtras().getStringArrayList(MineInfoActivity.INTENT_SELECTED_PICTURE).get(0);
                clipImage(mHeadUrl, mFilePath + mFilename);
            } else if (requestCode == MineInfoActivity.REQUEST_KEY) {
                //图片压缩上传 (80*80)
                setBitmapSize();
                sendRequest();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void sendRequest() {
        Account acct = AccountManager.getCurrentAccount();
        HeadUploadUtils.uploadHead(getActivity(), mFilePath + mFilename, new HeadUploadUtils.HeadUploadable() {
            @Override
            public void onSuccess(String url) {
                mUrlClubHead = url;
                ImageLoader.with(getContext())
                        .load(url)
                        .into(mImgCorpHead)
                        .start();
            }

            @Override
            public void onFailureUpload(Throwable t, int errorNo, String strMsg) {
            }
        });
    }

    private void setBitmapSize() {
        Bitmap userHeader = BitmapUtil.decodeBitmapFromFilePath(mFilePath + mFilename, 80, 80);
        BitmapUtil.saveBitmap(userHeader, mFilePath + mFilename, true);
    }

    private void clipImage(String url, String outputUrl) {
        int maxWidth = 0;
        int windowWidth = getActivity().getWindow().getWindowManager().getDefaultDisplay().getWidth();
        if (windowWidth <= 480) {
            maxWidth=100;
        }
        PhotoActionHelper.clipImage(getActivity())
                .input(url)
                .output(outputUrl)
                .maxOutputWidth(maxWidth)
                .requestCode(MineInfoActivity.REQUEST_KEY)
                .start(this);
    }
}
